package validate

import (
	"blog/errmsg"
	"blog/model"
	"github.com/go-playground/locales/zh"
	"github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	zh_translations "github.com/go-playground/validator/v10/translations/zh"
	"reflect"
)

/**
参数校验模块
//验证库：
// https://www.jianshu.com/p/9ef19d5eac72
// https://studygolang.com/articles/25825
 */

var validate = validator.New()

func Validate(data interface{})(string,int){
	var msg string
	var code int
	switch data.(type) {
	case *model.User:
		msg,code = validateUser(data.(*model.User))
	case *model.Article:

	case *model.ArticleCategory:

	case *model.Comment:

	default:

	}
	return msg,code
}

func validateUser(user *model.User)(string,int){
	//中文翻译器
	zh_ch := zh.New()
	uni_trans := ut.New(zh_ch)
	translator,_ := uni_trans.GetTranslator("zh")
	//验证器注册翻译器
	zh_translations.RegisterDefaultTranslations(validate,translator)

	//注册自定义的标签名称处理函数
	validate.RegisterTagNameFunc(func(field reflect.StructField) string {
		label := field.Tag.Get("label")
		return label
	})

	//结构体字段校验
	err := validate.Struct(user)
	if err!=nil{
		//var errMsg string
		for _,e := range err.(validator.ValidationErrors){
			//errMsg += e.Translate(translator) + " "
			return e.Translate(translator),errmsg.FAIL
		}
		//return errMsg,errmsg.FAIL
	}
	return "",errmsg.SUCCESS
}
